#include <Python.h>
#include <iostream>
#include<numpy/arrayobject.h>


using namespace std;

int main(){
	Py_SetPythonHome(L"/home/st/ubuntu_data/software/miniconda3/envs/ciassd_tra_pre"); //virtual enviroment path setting, otherwise don't work
	Py_Initialize(); //使用python前要调用此函数，进行初始化,开启虚拟机
	if( !Py_IsInitialized()){
		cout << "python init fail" << endl;
		return 0;
	}
	// PyRun_SimpleString("import torch");
	// PyRun_SimpleString("print(torch.__version__)");

	_import_array(); //PyArray_SimpleNewFromData之前必须先引入此函数

	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('/home/st/ubuntu_data/NRSL/little_project/cpp_learning/parallel_test/script')");

	PyObject* pModule = PyImport_ImportModule("class_test");
	if( pModule == NULL ){
		cout <<"module not found" << endl;
		return 1;
	}

	//模块的字典列表
	PyObject* pDict = PyModule_GetDict(pModule); //获得Python模块中的函数列
	if (pDict == NULL)
	{
		cout << "Can't find the dictionary!" << endl;
		return 0;
	}

	//获取YOLO类
	PyObject* pClassYOLO = PyDict_GetItemString(pDict, "yolo");//获取函数字典中的YOLO类
	if(pClassYOLO == NULL)
	{
		cout << "Can't find YOLO class!" << endl;
		return 0;
	}

	//构造YOLO类的实例
	PyObject* pInstanceYOLO = PyInstanceMethod_New(pClassYOLO);
	if (pInstanceYOLO == NULL)
	{
		cout << "Can't find YOLO instance!" << endl;
		return 0;
	}

	//读取图像并转换格式，opencv读取图像的存储格式是BGR格式，而PIL中为RGB，
	//本项目是用opencv读取图像，yolo3算法中用的是PIL格式，所以图像在传入yolo类之前需要先转换格式
	int m, n;
	m = 5; //行数
	n = 5 * 3; //列数*通道数
	unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * m * n);
	int num = 0;
	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < n; j++)
		{
			data[num] = 1;
			num++;
		}
	}
	npy_intp Dims[2] = { m,n };  //图像的维度信息
	PyObject* PyArray = PyArray_SimpleNewFromData(2, Dims, NPY_UBYTE, data); //建立函数的形参
	PyObject* ArgArray = PyTuple_New(1);//新建长度为1的元组
	PyTuple_SetItem(ArgArray, 0, PyArray);//设置元组ArgArray[0]为PyArray图像

	//调用YOLO实例对象的函数
	PyObject* pList = PyObject_CallMethod(pInstanceYOLO, "detect_image", "(OO)", pInstanceYOLO,  ArgArray); //pInstanceYOLO对应self，ArgArray对应image
	if(pList == NULL)
	{
		cout << "Failed to use fucntion!" << endl;
		return 0;
	}

	Py_DECREF(ArgArray);
	// Py_DECREF(PyArray);
	// Py_DECREF(pInstanceYOLO);
	// Py_DECREF(pDict);
	// Py_DECREF(pClassYOLO);
	// Py_DECREF(pModule);
	Py_Finalize();

	return 0;
}
